package com.wedo.mall.util;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.util.Base64;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Toast;

import com.e.library.utils.EUtils;
import com.wedo.mall.R;
import com.wedo.mall.entity.Goods;
import com.wedo.mall.entity.Shopping;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.lang.ref.WeakReference;
import java.util.List;

/**
 * @author lxy
 * @time 2017/7/3  18:09
 */
public final class WUtils {

    public static String toBase64(String path){
        try{

            Bitmap bitmap = convertToBitmap(path);
            return "data:image/jpeg;base64,"+Bitmap2Base64Str(bitmap);
        }catch (Exception e){
            return null;
        }
    }

    /**
     * 将Bitmap转换成Base64字符串
     * @param bit
     * @return
     */
    public static String Bitmap2Base64Str(Bitmap bit) {
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        bit.compress(Bitmap.CompressFormat.JPEG, 80, bos);// 参数100表示不压缩
        byte[] bytes = bos.toByteArray();
        return Base64.encodeToString(bytes, Base64.DEFAULT);
    }

    public static Bitmap convertToBitmap(String path) throws Exception{
        if (TextUtils.isEmpty(path) || !new File(path).exists()) {
            return null;
        }

        BitmapFactory.Options opts = new BitmapFactory.Options();
        // 设置为ture只获取图片大小
        opts.inJustDecodeBounds = true;
        opts.inPreferredConfig = Bitmap.Config.ARGB_4444;
        // 返回为空
        BitmapFactory.decodeFile(path, opts);
        int width = opts.outWidth;
        int height = opts.outHeight;
        float scaleWidth = 0.f, scaleHeight = 0.f;

        float scale = Math.max(scaleWidth, scaleHeight);
        opts.inJustDecodeBounds = false;
        opts.inSampleSize = (int)scale;
//        opts.inSampleSize = computeSampleSize(opts, -1, 1024*800);
//        opts.inJustDecodeBounds = false;
        WeakReference<Bitmap> weak = new WeakReference<Bitmap>(BitmapFactory.decodeFile(path, opts));
        return Bitmap.createScaledBitmap(weak.get(), width, height, true);
    }

    /**
     * 计算SampleSize，解决图片内存泄漏
     * @param options
     * @param minSideLength
     * @param maxNumOfPixels
     * @return
     */
    public static int computeSampleSize(BitmapFactory.Options options,
                                        int minSideLength, int maxNumOfPixels) {
        int initialSize = computeInitialSampleSize(options, minSideLength,
                maxNumOfPixels);

        int roundedSize;
        if (initialSize <= 8) {
            roundedSize = 1;
            while (roundedSize < initialSize) {
                roundedSize <<= 1;
            }
        } else {
            roundedSize = (initialSize + 7) / 8 * 8;
        }

        return roundedSize;
    }

    private static int computeInitialSampleSize(BitmapFactory.Options options,
                                                int minSideLength, int maxNumOfPixels) {
        double w = options.outWidth;
        double h = options.outHeight;

        int lowerBound = (maxNumOfPixels == -1) ? 1 : (int) Math.ceil(Math
                .sqrt(w * h / maxNumOfPixels));
        int upperBound = (minSideLength == -1) ? 128 : (int) Math.min(
                Math.floor(w / minSideLength), Math.floor(h / minSideLength));

        if (upperBound < lowerBound) {
            // return the larger one when there is no overlapping zone.
            return lowerBound;
        }

        if ((maxNumOfPixels == -1) && (minSideLength == -1)) {
            return 1;
        } else if (minSideLength == -1) {
            return lowerBound;
        } else {
            return upperBound;
        }
    }

    public static double toDouble(String str){
        try{
            return Double.parseDouble(str);
        }catch (Exception e){
            return 0.00;
        }
    }

    /**计算购物车商品总数量*/
    public static int goodsNumber(List<Shopping> list){
        if(EUtils.isEmpty(list)) {
            return 0;
        }

        int number = 0;
        for (Shopping shopping : list) {
            List<Goods> goodsList = shopping.goodsList;
            for (Goods goods : goodsList) {
                number += goods.goods_number;
            }
        }
        return number;

    }

    public static final int REQ_PHONE_CALL = 104;
    public static void requestPhoneCall(Activity activity, String phone){
        if(TextUtils.isEmpty(phone)) {
            Toast.makeText(activity,"没有联系方式",Toast.LENGTH_SHORT).show();
            return;
        }

        if(ActivityCompat.checkSelfPermission(activity, Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(activity, new String[]{Manifest.permission.CALL_PHONE},REQ_PHONE_CALL);
            return;
        }
        phoneCall(activity,phone);
    }

    public static void phoneCall(Activity activity, String phone){
        Intent intent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:"+phone));
        activity.startActivity(intent);
    }

    /**是否安装谷歌地图*/
    public static boolean isGoogleMapsInstalled(Context context) {
        try {
            ApplicationInfo info = context.getPackageManager().getApplicationInfo(
                    "com.google.android.apps.maps", 0);
            return true;
        } catch (PackageManager.NameNotFoundException e) {
            return false;
        }
    }

    public static void showTipsDialog(Context context){
        final AlertDialog.Builder builder = new AlertDialog.Builder(context);
        View view = LayoutInflater.from(context).inflate(R.layout.dialog_tips,null);
        builder.setView(view);
        final AlertDialog dialog = builder.create();
        view.findViewById(R.id.tv_confirm).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });
        dialog.show();
    }
}
